/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.givebonus.service.impl.GiveBonusServiceImpl
   Module Description   :

   Date Created      : 2010/2/4
   Original Author   : feeling.wang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.givebonus.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.givebonus.entity.GiveBonus;
import com.yaodian100.ec.givebonus.service.GiveBonusService;
import com.yaodian100.ec.member.entity.Bonus;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;

/**
 * @author feeling.wang
 * 
 */
public class GiveBonusServiceImpl extends DomainServiceImpl<GiveBonus> implements GiveBonusService {
	@Resource
	private TemplateService velocityService;
	@Resource
	private MailService mailService;
	@Resource
	private EnvParameters envParameters;
	private MemberService memberService;

	public MemberService getMemberService() {
		return memberService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.givebonus.service.GiveBonusService#saveGiveBonusBatch(java.util.List, java.io.File)
	 */
	@Override
	@Transactional(readOnly = false)
	public Map<String, Object> saveGiveBonus(GiveBonus giveBonus, File file, String fileName, String isSendMail) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			giveBonus = getDao().save(giveBonus);

			// file load
			StringBuilder filePath = new StringBuilder();
			filePath.append(ServerValue.getMidGiveBonusFile()).append(giveBonus.getUuid()).append(
					fileName.substring(fileName.lastIndexOf("."), fileName.length()));
			FileOutputStream fos = new FileOutputStream(filePath.toString());

			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			fos.close();
			fis.close();

			// read file
			List fileLists = FileUtils.readLines(file);
			List<Bonus> bonusList = new ArrayList<Bonus>();
			Bonus bonus = null;

			double totalGiveBouns = 0;
			int dataCount = fileLists.size();
			int successCount = 0;
			List ltmember = new ArrayList();
			for (Object fileList : fileLists) {
				String[] bounsInfo = StringUtils.split(((String) fileList), ",");
				if (bounsInfo.length >= 2) {
					if (bounsInfo[0].length() == 10) {
						String memberId = StringUtils.isBlank(bounsInfo[0]) ? "" : bounsInfo[0];
						ltmember.add(memberId);
						BigDecimal bounsAmt = StringUtils.isBlank(bounsInfo[1]) ? new BigDecimal(0) : new BigDecimal(bounsInfo[1]);
						ltmember.add(String.valueOf(bounsAmt));
						bonus = new Bonus();
						bonus.setDescription(giveBonus.getDescription());
						bonus.setExpireDate(giveBonus.getExpireDate());
						bonus.setMemberId(memberId);
						bonus.setStartDate(giveBonus.getStartDate());
						bonus.setTrxAmount(bounsAmt);
						bonus.setTrxDate(giveBonus.getTrxDate());
						bonus.setTrxType(giveBonus.getTrxType());
						if (bounsInfo.length == 3 && bounsInfo[2].length() == 13 && isNumeric(bounsInfo[2])) {
							bonus.setOrderId(bounsInfo[2]);
						}
						bonusList.add(bonus);
						totalGiveBouns += Double.parseDouble(bounsInfo[1]);
						successCount += 1;
					}
				}
			}
			memberService.saveOrUpdateBonusBatch(bonusList);
			result.put("totalGiveBouns", totalGiveBouns);
			result.put("dataCount", dataCount);
			result.put("successCount", successCount);
			filePath.setLength(0);
			if (isSendMail.equals("Y")) {
				sendMemberMail("bonusGenerateMail", ltmember, giveBonus, bonus);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	private boolean isNumeric(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	@Transactional(readOnly = false)
	public void sendMemberMail(String velocityTemplate, List ltmember, GiveBonus giveBonus, Bonus bonus)
			throws CoreException {
		try {
			Date dead3 = DateUtil.getTodayAddDays(1).getTime();
			dead3.setHours(1);
			dead3.setMinutes(0);
			dead3.setSeconds(0);
			Calendar cal = DateUtil.getTodayAddDays(1);
			cal.setTimeInMillis(dead3.getTime());
			cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, 1, 0);
			cal.setTimeInMillis(dead3.getTime());
			for (int i = 0; i < ltmember.size(); i += 2) {
				dead3 = cal.getTime();
				Member member = memberService.get(ltmember.get(i).toString());
				Map<String, Object> contentMap = new HashMap<String, Object>();
				contentMap.put("contextpath", ServerValue.getFrontContextPath());
				contentMap.put("basehref", "http://" + member.getDomainSrc());
				contentMap.put("endDate", FastDateFormat.getInstance("yyyy-MM-dd").format(giveBonus.getExpireDate()));
				contentMap.put("sysDate", FastDateFormat.getInstance("yyyy-MM-dd").format(dead3));
				contentMap.put("giveBonus", giveBonus);
				contentMap.put("bonus", bonus);
				contentMap.put("member", member);
				contentMap.put("trxAmoun", ltmember.get(i + 1));
				Mail mail = velocityService.formatToMail(velocityTemplate, contentMap);
				mail.setTo(member.getSendEmail());
				mail.setFrom(envParameters.getEmailFromSystem());
				mail.setSubject("积分发放通知 -" + giveBonus.getName() + "．耀点100");
				mail.setSendDT(dead3);
				mailService.save(mail);
				if ((i + 1) % 30 == 0) {
					cal.add(Calendar.MINUTE, 10);
				}
			}
		} catch (Exception e) {
			logger.error("err:" + e.getMessage());
		}
	}

	public EnvParameters getEnvParameters() {
		return envParameters;
	}

	public void setEnvParameters(EnvParameters envParameters) {
		this.envParameters = envParameters;
	}
}